﻿using System;
using System.Collections;
using Huirui.Cavan.Presentation.Seedwork;
using Huirui.Cavan.Domain.MainBoundedContext.PurchaseModule;
using Huirui.Cavan.Domain.MainBoundedContext.SearchModule;
using Huirui.Cavan.Presentation.ViewModel.PurchaseModule;
using Huirui.Cavan.Application.MainBoundedContext.PurchaseModule;
using System.Web.Mvc;
using Huirui.Cavan.Core.Extension;
using Huirui.Cavan.Domain.Seedwork;
using Huirui.Cavan.Application.MainBoundedContext.SystemModule;
using Huirui.Cavan.Application.MainBoundedContext.StockModule;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using Huirui.Cavan.Domain.MainBoundedContext.ReportModule;
using Newtonsoft.Json;
using Huirui.Cavan.Core.Helper;
using Huirui.Cavan.Domain.MainBoundedContext.SystemModule;

namespace Huirui.Cavan.Presentation.Controller.PurchaseModule
{
    #region PurchaseOrder

    public class PurchaseOrderController : EntityController<PurchaseOrder, string, PurchaseOrderSearch, IPurchaseOrderViewModel, IPurchaseOrderAppService>, IPurchaseOrderController
    {
        private ICurrencyAppService CurrencyAppService { get; set; }

        public override string ControllerName
        {
            get { return ControllerConst.PURCHASEORDER; }
        }

        public override bool UseDenied
        {
            get { return false; }
        }

        public PurchaseOrderController()
        {
            this.Model = ModelFactory.CreateModel<IPurchaseOrderViewModel>();
        }

        [ActionName(ActionConst.ADD)]
        [HttpGet]
        [ActionPermissionAttribute(Name = "purchaseorder_query")]
        public ActionResult AddPurchaseOrder(string id)
        {
            if (id.IsNotEmpty())
            {
                this.Model.Item = this.AppService.GetById(id);
            }
            else
            {
                this.Model.Item = new PurchaseOrder();
                this.Model.Item.PurchaseDate = DateTime.Now;
                this.Model.Item.DeliveryDate = DateTime.Now;
                this.Model.Item.Id = "";
                this.Model.Item.Currency = "CNY";
            }
            IList<Currency> currencies = this.CurrencyAppService.GetBySearch(new CurrencySearch()).ToList();
            this.Model.Currencies.Add(new SelectListItem() { Text = "请选择", Value = "1" });
            currencies.ForEach(c =>
            {
                this.Model.Currencies.Add(new SelectListItem() { Text = c.Code, Value = c.Rate.ToString() });
                if (id.IsEmpty() && c.IsLocal)
                {
                    this.Model.Currencies.FirstOrDefault(c1 => c1.Text == c.Code).Selected = true;
                    this.Model.Item.CurrencyRate = c.Rate;
                }
            });

            if (id.IsNotEmpty())
            {
                this.Model.Currencies.FirstOrDefault(c1 => c1.Value == this.Model.Item.Currency).Selected = true;
            }

            return View("~/Views/Purchase/v1/addPurchaseOrder.cshtml", this.Model);
        }

        [ActionName(ActionConst.ADD)]
        [HttpPost]
        [ActionPermissionAttribute(Name = "purchaseorder_edit")]
        public JsonResult AddPurchaseOrder(PurchaseOrderViewModel model)
        {
            BoolResult jsonResult = null;
            model.Item.PurchaseOrderDetails = JsonConvert.DeserializeObject<IList<PurchaseOrderDetail>>(model.PurchaseOrderDetails);

            BoolGenericResult<PurchaseOrder> result = this.AppService.AddOrUpdate(model.Item);
            jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult, "application/json");
        }

        [ActionName(ActionConst.MANAGE)]
        [ActionPermissionAttribute(Name = "purchaseorder_query")]
        public ActionResult GetPurchaseOrders()
        {
            return PartialView("~/Views/Purchase/v1/managePurchaseOrder.cshtml");
        }

        [ActionName(ActionConst.LIST)]
        [ActionPermissionAttribute(Name = "purchaseorder_query")]
        public JsonResult GetPurchaseOrders(PurchaseOrderViewModel model)
        {
            PurchaseOrderSearch search = model.SearchParam;
            string id = Request["SearchParam.ID"].ToString();
            PurchaseOrderManageJsonViewModel json = new PurchaseOrderManageJsonViewModel();
            json.rows = new List<PurchaseOrderManageReport>();

            long total = 0;
            IList<PurchaseOrderManageReport> purchaseOrderManageReports = this.AppService.GetPurchaseOrderManageReport(search.StartDate, search.EndDate, search.SupplierCode,
                search.ID, search.SupplierInvoiceNumber, search.PurchaseEmployeeCode, search.WareHouseCode, StringHelper.ClearLastChar(search.CheckStatues), StringHelper.ClearLastChar(search.StoskInStatues));
            foreach (PurchaseOrderManageReport po in purchaseOrderManageReports)
            {
                po.CheckedStatus = Huirui.Cavan.Presentation.Seedwork.Ext.GetEnumDescription(typeof(SystemIdentifier.CheckedStatus), po.CheckedStatus);
                po.StockInStatus = Huirui.Cavan.Presentation.Seedwork.Ext.GetEnumDescription(typeof(PurchaseIdentifier.StockInStatus), po.StockInStatus);
                json.rows.Add(po);
            }
            json.total = purchaseOrderManageReports.IsNotNull() ? purchaseOrderManageReports.Count : 0;

            return Json(json, "application/json");
        }

        [ActionName(ActionConst.CLOSE)]
        [ActionPermissionAttribute(Name = "purchaseorder_edit")]
        public JsonResult UpdatePurchaseOrderToClose(string id)
        {
            PurchaseOrder purchaseOrder = this.AppService.GetById(id);
            BoolGenericResult<PurchaseOrder> result = this.AppService.UpdatePurchaseOrderStatus(purchaseOrder, PurchaseIdentifier.StockInStatus.Closed);
            BoolResult json = new BoolResult(result.IsSuccess, result.Messages);

            return Json(json, "application/json");
        }

        [ActionName(ActionConst.OPEN)]
        [ActionPermissionAttribute(Name = "purchaseorder_edit")]
        public JsonResult UpdatePurchaseOrderToOpen(string id)
        {
            PurchaseOrder purchaseOrder = this.AppService.GetById(id);
            BoolGenericResult<PurchaseOrder> result = this.AppService.UpdatePurchaseOrderStatus(purchaseOrder, PurchaseIdentifier.StockInStatus.UnIn);
            BoolResult json = new BoolResult(result.IsSuccess, result.Messages);

            return Json(json, "application/json");
        }

        [ActionName("listbyselect")]
        [ActionPermissionAttribute(Name = "purchaseorder_query")]
        public JsonResult GetPurchaseOrder(string selected)
        {
            PurchaseOrderJsonViewModel json = new PurchaseOrderJsonViewModel();
            json.rows = new List<PurchaseOrderJson>();
            List<StockByPurchaseOrderReport> purchaseOrders = JsonConvert.DeserializeObject<List<StockByPurchaseOrderReport>>(selected);

            foreach (StockByPurchaseOrderReport po in purchaseOrders)
            {
                PurchaseOrder purchaseOrder = this.AppService.GetById(po.PurchaseOrderCode);
                PurchaseOrderJson poj = new PurchaseOrderJson();
                poj = Mapper.Map<PurchaseOrder, PurchaseOrderJson>(purchaseOrder);
                json.rows.Add(poj);
            }
            json.total = purchaseOrders.Count;

            return Json(json, "application/json");
        }
    }
    #endregion
}